package cn.edu.seu.herald.informationplatform.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import cn.edu.seu.herald.informationplatform.bean.league.Album;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.database.AlbumDao;
import cn.edu.seu.herald.informationplatform.util.filetools.PicTools;


public class AlbumEdit extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public AlbumEdit() {
		super();
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		try{
			AlbumDao albumDao = AlbumDao.getDao();
			int albumId = 0;
			Album preAlbum = null;
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (!isMultipart) {
				System.out.println("File Not Uploaded");
			} else {
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
			    List<?> items = null;
			    try {
				items = upload.parseRequest(request);
				} catch (FileUploadException e) {
				e.printStackTrace();
				}
				Iterator<?> itr = items.iterator();
				while (itr.hasNext()) {		    
				FileItem item = (FileItem) itr.next();
				if(item.getFieldName().equals("album")){
					albumId = Integer.parseInt(item.getString());
					preAlbum = albumDao.getAlbumById(albumId);
				}
						  if(item.getFieldName().equals("picName")){
							  preAlbum.setName(item.getString(request.getCharacterEncoding())); 							  
						  if(itr.hasNext()){  
							  FileItem itemPic = (FileItem) itr.next();
							  if (!itemPic.isFormField()){
								  System.out.println("HERE");
								  String itemName = FilenameUtils.getName(itemPic.getName());
								  
								  Random generator = new Random();
								  int r = Math.abs(generator.nextInt());

								  String reg = "[.*]";
								  String replacingtext = "";
								  
								  Pattern pattern = Pattern.compile(reg);
								  Matcher matcher = pattern.matcher(itemName);
								  StringBuffer buffer = new StringBuffer();

								  while (matcher.find()) {
								  matcher.appendReplacement(buffer, replacingtext);
								  }
								  int IndexOf = itemName.indexOf("."); 
								  String preFileName = itemName.substring(IndexOf);
								  /*System.out.println("preFileName: "+preFileName);
					              System.out.println("fileName:" + buffer.toString());
					              System.out.println("fileType:" + item.getContentType());
					              System.out.println("fileSize:" + item.getSize() + "byte");*/
								  String finalimage = buffer.toString()+"_"+r+preFileName;
								  System.out.println("Final Image==="+finalimage);
								  String path = getServletContext().getRealPath("/");
								  Properties pro = System.getProperties();
							         String osName = pro.getProperty("os.name");
							         File saveFile = null;
							         String savePath = null;
							         String relativeSavePath = null;
							         
							         if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
							        	 savePath = path+"/pictures/"+finalimage;
							        	 saveFile = new File(savePath); 
							        	
							         }
							         else{
							        	 savePath = path+"pictures\\"+finalimage;
							        	 saveFile = new File(savePath);
							         }
							         relativeSavePath = "pictures/"+finalimage;
								  itemPic.write(saveFile);
								  PicTools.correctPicSize(savePath);
								  preAlbum.setCoverPicAddress(relativeSavePath);
							  }
						  }
						  }
				}
			}
			albumDao.updateAlbum(albumId,preAlbum);
		    LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
			response.sendRedirect("./albums.jsp?league="+luSessionCookieAccess.getLeagueId());

		}catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
